#include "Server.hpp"
void HandleRead(Channel* channel)
{
    // 1. 接收socket的数据，放到缓冲区
    char buf[65536];
    ssize_t ret = recv(channel->Fd(), buf, sizeof(buf) - 1, 0);
    if (ret < 0)
    {
        //
    }
    printf("%s", buf);
    channel->EnableWrite();
    
}
// 描述符可写事件触发后调用的函数，将发送缓冲区中的数据进行发送
void HandleWrite(Channel* channel)
{
    //_out_buffer中保存的数据就是要发送的数据
    char buf[256];
    sprintf(buf, "你好。。。。。\n");
    ssize_t ret = send(channel->Fd(), buf, sizeof(buf), 0);
    channel->DisableWrite();
}
// 描述符触发挂断事件
void HandleClose(Channel* channel)
{
    close(channel->Fd());
    channel->Remove();
    std::cout << "连接挂断" << std::endl;
}
// 描述符触发出错事件
void HandleError(Channel* channel)
{
    return HandleClose(channel);
}
void HandleEvery(EventLoop* loop, Channel* channel)
{
    
}
void acceptor(Socket::ptr& sock, EventLoop *loop)
{
    int newfd = sock->Accept();
    std::cout << newfd << std::endl;
    Channel *newchannel = new Channel(loop, newfd);
    
    newchannel->SetReadCallback(std::bind(HandleRead, newchannel));
    newchannel->SetWriteCallback(std::bind(HandleWrite, newchannel));
    newchannel->SetCloseCallback(std::bind(&HandleClose, newchannel));
    newchannel->SetErrorCallback(std::bind(&HandleError, newchannel));
    newchannel->EnableRead();
    loop->AddTimerTask(std::bind(HandleClose, newchannel), newfd, 10);
}


int main()
{
    EventLoop loop;
    // Socket s;
    auto s = std::make_shared<Socket>();

    s->CreateServer(8889); // 创建监听套接字并开启监听状态
    std::cout << s->Fd() << std::endl;

    
    Channel channel(&loop, s->Fd());
    channel.EnableRead();

    // // 使用std::ref 
    // channel.SetReadCallback(std::bind(acceptor, std::ref(s), &loop));

    // 
    channel.SetReadCallback(std::bind(acceptor, s, &loop)); // 进行回调函数绑定
    channel.SetEventCallback(std::bind(&EventLoop::RefreshTimerTask, &loop, channel.Fd()));
    loop.AddTimerTask(std::bind(HandleClose, &channel), s->Fd(), 16);
    int i = 0;
    while(++i)
    {
        loop.Start();
    }
    // int epfd = epoll_create(1);
    // struct epoll_event ev;
    // ev.data.fd = s.Fd();
    // ev.events = EPOLLIN;
    // struct epoll_event actives[1024];
    // int ret = epoll_ctl(epfd, EPOLL_CTL_ADD, s.Fd(), &ev);
    // if(ret < 0){
    //     std::cout << "epoll_ctl error" << std::endl;
    // }
    // while(1)
    // {
    //     int n = epoll_wait(epfd, actives, 1024, -1);
    //     for(int i = 0; i < n; i++){
    //         std::cout << actives->data.fd << std::endl;
    //         if(actives->data.fd == s.Fd()){
    //             int newfd = s.Accept();
    //             std::cout << "获取新连接：" << newfd << std::endl;
    //         }
    //     }
    // }
    return 0;
}
